﻿using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;

namespace FootSteps.Data
{
    public class PrintScreenLogImage
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        [ForeignKey("PrintScreenLog")]
        public int PrintScreenLogId { get; set; }
        
        //[Required]
        public PrintScreenLog PrintScreenLog { get; set; }

        [MaxLength][Required]
        public byte[] ImageBytes { get; set; }
        
        public bool IsCompressed { get; set; }

        public void Compress()
        {
            if (IsCompressed) return;
            ImageFormat usedFormat;
            var allBytes = new[] {ImageFormat.Bmp, ImageFormat.Png, ImageFormat.Tiff }.Select(imageFormat =>
            {
                using (var formatStream = new MemoryStream())
                using (var bytes = new MemoryStream(ImageBytes))
                using (var bpm = new Bitmap(bytes))
                {
                    bpm.Save(formatStream, imageFormat);
                    return new
                    {
                        Bytes = formatStream.ToArray(),
                        Format = imageFormat
                    };
                }
            }).OrderBy(i => i.Bytes.Length).ToArray();

            usedFormat = allBytes.First().Format;
            var newBytes = SevenZipHelper.Compress(allBytes.First().Bytes);
            Console.WriteLine("Compression Finished. Original {0}, Current {1}, Format {2}", ImageBytes.Length,
                newBytes.Length, usedFormat);
            ImageBytes = newBytes;

            IsCompressed = true;

        }

        public void Decompress()
        {
            if (!IsCompressed) return;
            
            ImageBytes = SevenZipHelper.Decompress(ImageBytes);

            IsCompressed = false;
        }

        
        public override string ToString()
        {
            return string.Format("Compressed: {0}. Bytes Size: {1} Kbs",
                IsCompressed, ImageBytes.Length / 1024d);
        }

        public Bitmap GetBitmapFromBytes()
        {
            Decompress();
            using (var original = new Bitmap(new MemoryStream(ImageBytes)))
            {
                var bitmap = new Bitmap(1024, 576);
                using (var g = Graphics.FromImage(bitmap))
                {
                    g.DrawImage(original, 0, 0);
                }
                return bitmap;
            }

        }
        
    }
}